
const db = require("../initDB")
const UserModel = require("../models/users")
const userModel = UserModel(db);
const RangModel = require("../models/ranking")
const rangModel = RangModel(db)
const { loginSchema } = require("../schema/user")

const jwt = require("../Jwt/jwt")
const Login = async (req, res) => {
    const jsonData = req.body;


    try {
        const value = await loginSchema.validateAsync(jsonData)
    } catch (err) {
        res.validateError(res, err.toString())
        return
    }


    // if (!jsonData.mobile) {
    //     res.validateError(res)
    //     return
    // }
    // if (!jsonData.password) {
    //     res.validateError(res)
    //     return
    // }

    //根据手机号查找用户
    let user = await userModel.findOne({ where: { name: jsonData.name } });

    if (!user) {
        try {
            // 注册
            user = await userModel.create({
                "name": jsonData.name,
                "mobile": "",
                "password": jsonData.password,
                "currentRanking": "",
                "highestScore": "",
            })
        } catch (err) {
            console.log("err", err)
            res.otherError(res, err.toString())
            return
        }

    } else {

        if (user.password !== jsonData.password) {
            res.otherError(res, "密码错误")
            return;
        }

    }

    let data = { ...user.toJSON() }
    data[`token`] = jwt.sign(user.id);
    res.SendSuccess(res, data)

}


const getUserInfo = async (req, res) => {

    let id = jwt.getUserId(req)
    if (!id) {
        res.otherError(res, "用户不存在")
        return
    }
    let userRangList = await rangModel.findOne({
        where: {
            userId: id
        },
        order: [
            ['score', "DESC"]
        ],
    })

    let user = await userModel.findOne({
        where: {
            id
        }
    })
    if (!user) {
        res.otherError(res, "用户不存在");
        return
    }
    // console.log("userRangList", userRangList)
    user.highestScore = userRangList?.score || "0";

    res.SendSuccess(res, user)

}

module.exports = {
    Login,
    getUserInfo
}